package com.yehun.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 序列化
 * Created by Genius on 2017/3/27 0027.
 */
public class SerializeUtils {

    private static final Logger logger = LoggerFactory.getLogger(SerializeUtils.class);

    public static byte[] serialize(Object object) {
        ObjectOutputStream objectsteam;
        ByteArrayOutputStream bytearraysteam;
        try {
            bytearraysteam = new ByteArrayOutputStream();
            objectsteam = new ObjectOutputStream(bytearraysteam);
            objectsteam.writeObject(object);
            return bytearraysteam.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object deserialize(byte[] bytes) {
        ByteArrayInputStream bytearraysteam;
        try {
            bytearraysteam = new ByteArrayInputStream(bytes);
            ObjectInputStream objectsteam = new ObjectInputStream(bytearraysteam);
            return objectsteam.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("unused,unchecked")
    public static <T> T deserialize(byte[] bytes, Class<T> type) {
        ByteArrayInputStream bytearraysteam;
        try {
            bytearraysteam = new ByteArrayInputStream(bytes);
            ObjectInputStream objectsteam = new ObjectInputStream(bytearraysteam);
            return (T) objectsteam.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        TestS testS = new TestS("123");
        byte[] bytes = serialize(testS);
        Object object = deserialize(bytes);

        logger.info("type => " + object.getClass().getName());
        logger.info("object => " + ((TestS)object).name);

        TestS testS1 = deserialize(bytes, TestS.class);
        logger.info("type => " + testS1.getClass().getName());
        logger.info("object => " + testS1.name);

    }


    static class TestS implements Serializable {

        public TestS() { }
        public TestS(String name) {
            this.name = name;
        }
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }



}
